package broker

import (
	"context"
	"github.com/asim/go-micro/plugins/broker/rabbitmq/v4"
	"go-micro.dev/v4/broker"
	"manager/config"
	"manager/utils"
)

var defaultRabbitMQAddress = "amqp://guest:guest@localhost:5672"

func InitRabbit() broker.Broker {
	if config.Conf.Broker.Addr != "" {
		defaultRabbitMQAddress = config.Conf.Broker.Addr
	}

	b := rabbitmq.NewBroker(broker.Addrs(defaultRabbitMQAddress))
	utils.Throw(b.Connect())
	return b
}

func InitAliRabbit() broker.Broker {
	if config.Conf.Broker.Addr != "" {
		defaultRabbitMQAddress = config.Conf.Broker.Addr
	}

	b := NewBroker(broker.Addrs(defaultRabbitMQAddress))
	utils.Throw(b.Connect())

	/*	go func() {
		defer utils.ExceptionCatch()
		// test
		_defaultRabbitMQAddress := "amqp://MjphbXFwLWNuLW53eTM4bXVscTAwNTpMVEFJNXQ2R2pmekgzcmJNb0FTdTFTemI=:OUY4OTcwRjNBRkY3MDBEQ0MzQkZFNzBFNzE2QzBCRjg3NjhDNUE2ODoxNjg1Njc1NjAwMjY3@amqp-cn-nwy38mulq005.cn-hangzhou.amqp-7.net.mq.amqp.aliyuncs.com:5672/"
		//_defaultRabbitMQAddress := "amqp://guest:guest@192.168.246.128:5672/"
		testBroker := NewBroker(broker.Addrs(_defaultRabbitMQAddress))
		utils.Throw(testBroker.Connect())

		var syncWait sync.WaitGroup
		syncWait.Add(1)
		// 订阅
		testBroker.Subscribe("test_public", func(event broker.Event) error {
			fmt.Println("---------- rabbitmq test consumer 公网 ", string(event.Message().Body))
			return nil
		})

		time.Sleep(time.Second * 10)

		for i := 0; i < 1; i++ {
			fmt.Println("---------- rabbitmq test producer 公网 ", i, testBroker.Publish("test_public", &broker.Message{
				Body: []byte(fmt.Sprintf("test_public %d", i)),
			}))
			time.Sleep(time.Millisecond * 100)
		}
		syncWait.Wait()
	}()*/
	return b
}

func NewBroker(opts ...broker.Option) broker.Broker {
	options := broker.Options{
		Context: context.Background(),
	}

	for _, o := range opts {
		o(&options)
	}

	broker := &AmqpRabbitMq{
		addrs: options.Addrs,
		opts:  options,
	}
	broker.Init(opts...)
	return broker
}
